import { BasicClassValueField } from "@@/apis/basic-data/types";
import { BSDataTypeEnum, RecordTypeEnum } from "@@/constants/other-keys";

// 改进的 JSON 字符串判断函数
export const isJSON = (str: unknown): boolean => {
  if (typeof str !== "string") return false;
  const trimmed = str.trim();

  // 快速格式检查
  if (!trimmed || !(trimmed.startsWith('{') || trimmed.startsWith('['))) return false;

  try {
    // 处理循环引用和特殊结构
    const replacedStr = trimmed.replace(
      /"(?:pageInfo|\$ref)":\s*(?:"\@"|{[^}]*"@"[^}]*})/g,
      '"pageInfo":null'
    );
    JSON.parse(replacedStr);
    return true;
  } catch {
    return false;
  }
};

// 安全的 JSON 解析函数
const safeJSONParse = (str: string): any => {
  try {
    const replacedStr = str.replace(
      /"(?:pageInfo|\$ref)":\s*(?:"\@"|{[^}]*"@"[^}]*})/g,
      '"pageInfo":null'
    );
    return JSON.parse(replacedStr);
  } catch {
    return null;
  }
};

// 递归获取值
const getDeepValue = (obj: any): string => {
  if (!obj) return "";
  if (typeof obj === "string") return obj;
  if (Array.isArray(obj)) {
    return obj.map(item => getDeepValue(item)).filter(Boolean).join("; ");
  }
  if (obj.value !== undefined) return obj.value;
  if (obj.children?.length) {
    return obj.children.map((child: any) => getDeepValue(child)).filter(Boolean).join(obj.separator || "_");
  }
  return "";
};

// 获取基础记录值
export function getRecordBaseValue(item: BasicClassValueField): string {
  if (!item?.value) return "";
  if (!isJSON(item.value)) return item.value;

  const parsed = safeJSONParse(item.value);
  if (!parsed) return item.value;

  const itemType = item.type || item.field?.type;
  const separator = item.separator || ",";

  // 处理基础类型和枚举类型
  if (itemType === BSDataTypeEnum.Base || itemType === BSDataTypeEnum.Enum) {
    return getDeepValue(parsed);
  }

  // 处理类类型
  if (itemType === BSDataTypeEnum.Class) {
    const valueItems = item.children?.length ? item.children : parsed;
    return Array.isArray(valueItems)
      ? valueItems.map(prop => getDeepValue(prop)).filter(Boolean).join(separator)
      : getDeepValue(valueItems);
  }

  return item.value;
}

// 获取数组记录值
export function getRecordArrayValue(item: BasicClassValueField): string {
  if (!item?.value) return "";
  if (!isJSON(item.value)) return item.value;

  const parsed = safeJSONParse(item.value);
  if (!parsed || !Array.isArray(parsed)) return item.value;

  return parsed
    .map(valueItem => getRecordBaseValue(valueItem))
    .filter(Boolean)
    .join("; ");
}

// 主解析函数
export function parseParmeValue(item: BasicClassValueField): string {
  if (!item?.value) return "";

  const recordType = item.recordType || item.field?.recordType;

  switch (recordType) {
    case RecordTypeEnum.Base:
      return getRecordBaseValue(item);
    case RecordTypeEnum.Array:
      return getRecordArrayValue(item);
    default:
      return "";
  }
}